package com.teamclub.app.sconfs

import java.util

import com.teamclub.app.sconfs.oauth.{OAuth2Filter, OAuth2Realm}
import javax.servlet.Filter
import org.apache.shiro.mgt.SecurityManager
import org.apache.shiro.spring.LifecycleBeanPostProcessor
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor
import org.apache.shiro.spring.web.ShiroFilterFactoryBean
import org.apache.shiro.web.mgt.DefaultWebSecurityManager
import org.springframework.context.annotation.{Bean, Configuration}
import org.springframework.stereotype.Component

@Configuration
class ShiroConfig {
  @Bean(Array("securityManager"))
  def securityManager(oAuth2Realm: OAuth2Realm): SecurityManager = {
    val securityManager = new DefaultWebSecurityManager
    securityManager.setRealm(oAuth2Realm)
    securityManager.setRememberMeManager(null)
    securityManager
  }

  @Bean(Array("shiroFilter"))
  def shirFilter(securityManager: SecurityManager): ShiroFilterFactoryBean = {
    val shiroFilter: ShiroFilterFactoryBean = new ShiroFilterFactoryBean
    shiroFilter.setSecurityManager(securityManager)
    //oauth过滤
    val filters: util.Map[String, Filter] = new util.HashMap[String, Filter]
    filters.put("oauth2", new OAuth2Filter)
    shiroFilter.setFilters(filters)
    val filterMap: util.Map[String, String] = new util.LinkedHashMap[String, String]
    filterMap.put("/webjars/**", "anon")
    filterMap.put("/druid/**", "anon")
    filterMap.put("/app/**", "anon")
    filterMap.put("/sys/login", "anon")
    filterMap.put("/swagger/**", "anon")
    filterMap.put("/v2/api-docs", "anon")
    filterMap.put("/swagger-ui.html", "anon")
    filterMap.put("/swagger-resources/**", "anon")
//    filterMap.put("/captcha.jpg", "anon")
    filterMap.put("/**", "oauth2")
    shiroFilter.setFilterChainDefinitionMap(filterMap)
    shiroFilter
  }

  @Bean(Array("lifecycleBeanPostProcessor"))
  def lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor

  @Bean
  def authorizationAttributeSourceAdvisor(securityManager: SecurityManager): AuthorizationAttributeSourceAdvisor = {
    val advisor = new AuthorizationAttributeSourceAdvisor
    advisor.setSecurityManager(securityManager)
    advisor
  }
}